<?php
/**
 * 使用Memcache扩展从TTServer获取数据
 * $objRpc = new Rpc_Ttserver('reco', array(array('host' => '220.181.112.138', 'port' => 20010)));
 * $strContent = $objRpc->call(
 * 		array(
 * 			'action' => 'homepage_spotlight_rec',
 * 		)
 * );
 * $arrContent = $objRpc->call(
 * 		array(
 * 			'action' => array('homepage_spotlight_rec', homepage_trend_rec'),
 * 		)
 * );
 * @author wulijun
 *
 */
class Rpc_Ttserver extends Rpc_Abstract {
	protected $_objMemcache = null;

	/**
	 * @param array $arrInput array(
	 * 		'action' => strKey | array(strKey1, strKey2, ...)
	 * )
	 * @return 失败返回false，成功返回从Ttserver取回的数据，如果action是strKey，则返回值是TTServer中该
	 * 		strKey对应的值；如果是array(strKey1, ...)形式，则返回值为key/value形式的数组，参考Memcache::get。
	 * @see Rpc_Abstract::call()
	 */
	public function call($arrInput, $intRetry = 1) {
		$arrOutput = false;
        while ($intRetry--) {
        	$bolConn = $this->connect();
        	if (! $bolConn) {
        		continue;
        	}
			$arrOutput = $this->_objMemcache->get($arrInput['action']);
			if ($arrOutput !== false) {
				break;
			}
        }

        return $arrOutput;	
	}

	/**
	 * 对TTServer做更新相关的操作
	 */
	public function doOp($arrInput, $intRetry = 1) {
		$arrOutput = false;
        while ($intRetry--) {
        	$bolConn = $this->connect();
        	if (! $bolConn) {
        		continue;
        	}
			$arrOutput = call_user_func_array(array($this->_objMemcache, $arrInput['action']), $arrInput['args']);
			if ($arrOutput !== false) {
				break;
			}
        }

        return $arrOutput;			
	}

	public function realConnect($arrServer) {
		if (! isset($arrServer['host']) || ! isset($arrServer['port'])) {
			return false;
		}
		$objMemcache = new Memcache();
		$bolConn = $objMemcache->connect($arrServer['host'], $arrServer['port']);
	
		if (! $bolConn) {
			return false;
		} else {
			$this->_objMemcache = $objMemcache;
			$this->_arrNowServer = $arrServer;
			return true;
		}	
	}
}
